﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using MoneyWentWhere.Utils;
using System.Collections;

namespace MoneyWentWhere.OutputHelpers
{
    public class ObjectFieldColumn : MultiColumn
    {
        public ObjectFieldColumn(TableOptions options)
            : base(options)
        {
        }

        protected override void InitializeSubcolumns<T>(IEnumerable<T> rows)
        {
            Columns = new List<Column>();

            // Examine the type to detemine columns
            Type rowType = typeof(T);
            FieldInfo[] fields = rowType.GetFields();

            foreach (FieldInfo f in fields)
            {
                // Ignore some fields
                if (f.HasAttribute<DisplayIgnoreAttribute>()) { continue; }

                Column col;
                if (typeof(IDictionary).IsAssignableFrom(f.FieldType))
                {
                    // Dictionary field
                    col = new DictionaryColumn(TableOptions, f);
                }
                else
                {
                    // Regular field
                    col = new FieldValueColumn(TableOptions, f);
                }
                Columns.Add(col);
            }
        }
    }

    public class FieldValueColumn : ValueColumn
    {
        public readonly FieldInfo Field;

        public FieldValueColumn(TableOptions options, FieldInfo field)
            : base(options, field)
        {
            Field = field;
            Header = Field.Name;
        }

        public override object GetValue<T>(T row)
        {
            return Field.GetValue(row);
        }

    }
}
